package com.kirk.cts.core.base.pagination.util;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.log4j.Logger;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * <p> DruidDbPool.java </p>
 *
 * @version 1.0.0
 * @Author kirkliu
 * @Date 2020-08-31 23:11
 * @Description Druid
 */
public class DruidDbPool implements DbPool {
    protected Logger logger = Logger.getLogger(this.getClass());
    private static DruidDataSource dataSource = null;
    private String name;
    private String url;

    public DruidDbPool(String name, String url, String user,
                       String password, int maxConn, String className) {
        this.name = name;
        this.url = url;
        dataSource = new DruidDataSource();
        dataSource.setDriverClassName(className);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        dataSource.setInitialSize(5);
        dataSource.setMinIdle(1);
        dataSource.setMaxActive(maxConn);

        dataSource.setPoolPreparedStatements(false);
    }

    /**
     * 从连接池获取可用连接.可以指定客户程序能够等待的最长时间 参见前一个getConnection()方法.
     *
     * @param timeout 以毫秒计的等待时间限制
     */
    public synchronized Connection getConnection(long timeout) {
        return newConnection();
    }


    /**
     * 创建新的连接
     */
    private synchronized Connection newConnection() {
        Connection con = null;
        try {
            con = dataSource.getConnection();
            logger.info("连接池" + name + "创建一个新的连接");
        } catch (SQLException e) {
            logger.error("无法创建下列URL的连接: " + url);
            logger.error(e);
            return null;
        }
        return con;
    }

    @Override
    public synchronized void freeConnection(Connection con) {
        try {
            con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public synchronized Connection getConnection() {
        return newConnection();
    }

    @Override
    public synchronized void release() {
        dataSource.close();
    }
}
